package com.aaa.charge.service.impl;

import com.aaa.charge.dao.ChargeDao;
import com.aaa.charge.service.OrderChargeService;
import com.aaa.charge.util.HttpClient;
import com.aaa.charge.vo.OrderChargeVo;
import com.aaa.charge.vo.PostObjectVo1;
import com.aaa.entity.OrderCharge;
import com.aaa.entity.OrderChargeItem;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author pzs
 * @date 2023/3/24 11:23
 * @description OrderChargeService
 */
@Service
public class ChargeServiceImpl implements OrderChargeService {
    @Resource
    private ChargeDao orderChargerDao;

    @Value("${weixin.appid}")
    private String appId;
    @Value("${weixin.mch_id}")
    private String mchId;
    @Value("${weixin.api_key}")
    private String apiKey;

    @Override
    public Result<IPage<OrderCharge>> findAllCharge(Integer currentPage, Integer pageSize, OrderChargeVo orderChargeVo) {
        IPage<OrderCharge> page=new Page<>(currentPage,pageSize);
        QueryWrapper<OrderCharge> wrapper=new QueryWrapper<>();
        if(StringUtils.hasText(orderChargeVo.getPatientName())){
            wrapper.like("patient_name",orderChargeVo.getPatientName());
        }
        if(StringUtils.hasText(orderChargeVo.getRegId())){
            wrapper.eq("reg_id",orderChargeVo.getRegId());
        }
        IPage<OrderCharge> page1=orderChargerDao.selectPage(page,wrapper);

        return new Result<IPage<OrderCharge>>(200,"查询用户成功",page1);
    }
    //现金
    @Override
    public Result<Integer> upByOrderId(String orderId) {
        Integer i= orderChargerDao.updateByOrderId(orderId);
        return new Result<>(i);
    }

    //微信
    @Override
    public Result selectAll(String orderId)  {
        // 根据前来传过来的参数获取患者名称
        QueryWrapper<OrderCharge> queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_id",orderId);
        OrderCharge orderCharge = orderChargerDao.selectOne(queryWrapper);
        String patientName = orderCharge.getPatientName();
        //获取总金额
        BigDecimal orderAmount = orderCharge.getOrderAmount();
        try {
            // 设置请求的参数
            HashMap<String, String> map = new HashMap<>();
            map.put("appid",appId);
            map.put("mch_id",mchId);
            map.put("nonce_str", WXPayUtil.generateNonceStr());
            map.put("body",patientName);
            map.put("out_trade_no",orderId);
            //支付金额设置成0.01，毕竟钱不是大风刮来的
            map.put("total_fee",new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue()+"");
            map.put("spbill_create_ip","127.0.0.1");
            map.put("notify_url","http:localhost:8080/charge/docharge");
            map.put("trade_type", "NATIVE");
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //支持https协议
            client.setHttps(true);
            //设置请求参数
            client.setXmlParam(WXPayUtil.generateSignedXml(map, apiKey));
            //发送请求
            client.post();
            //获取请求的响应结果
            String content = client.getContent();

            //装换为map格式
            Map<String, String> stringMap = WXPayUtil.xmlToMap(content);
            if (stringMap.get("result_code").equals("SUCCESS")) {
                Map<String, Object> result = new HashMap<>();
                result.put("codeUrl", stringMap.get("code_url"));
                result.put("price", orderAmount);
                result.put("orderId", orderId);
                return new Result(200,"生成二维码成功",result);
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(200,"订单失效了",null);
    }
    //根据订单查询支付状态
    @Override
    public Result queryPayStatus(String orderId) {
        Boolean flag=false;
        try {
            //根据订单状态查询微信的支付的状态
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            Map<String, String> params = new HashMap<>();
            params.put("appid", appId);
            params.put("mch_id", mchId);
            params.put("out_trade_no", orderId);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            client.setHttps(true);
            client.setXmlParam(WXPayUtil.generateSignedXml(params,apiKey));
            client.post();
            String content = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if (map.get("trade_state").equals("SUCCESS")){
                flag=true;
                //1修改订单状态
                orderChargerDao.updateOrderId(orderId);
                return  new Result(200,"支付成功",flag);
            }
        }catch (Exception e){

        }
        return  new Result(200,"请扫码二维码支付",flag);
    }
}
